#include "databaseconfig.h"
#include <QFile>
#include <QSettings>
#include <QDebug>

// 构造函数：初始化父对象
DatabaseConfig::DatabaseConfig(QObject *parent) : QObject(parent)
{
    // 成员变量的默认值已在头文件中初始化
}

// 从配置文件加载参数（支持.ini格式）
bool DatabaseConfig::loadConfig(const QString &configPath)
{
    // 检查配置文件是否存在
    if (!QFile::exists(configPath)) {
        qWarning() << "配置文件不存在：" << configPath;
        return false;
    }

    // 读取.ini格式配置文件
    QSettings settings(configPath, QSettings::IniFormat);

    // 读取基本数据库配置项（第二个参数是默认值）
    m_host = settings.value("Database/Host", "localhost").toString();
    m_port = settings.value("Database/Port", 3306).toInt();
    m_databaseName = settings.value("Database/Name", "supermarket_db").toString();
    m_userName = settings.value("Database/User", "root").toString();
    m_password = settings.value("Database/Password", "123456").toString();
    
    // 读取连接选项配置
    m_connectTimeout = settings.value("ConnectionOptions/ConnectTimeout", 30).toInt();
    m_readTimeout = settings.value("ConnectionOptions/ReadTimeout", 60).toInt();
    m_writeTimeout = settings.value("ConnectionOptions/WriteTimeout", 60).toInt();
    m_useSSL = settings.value("ConnectionOptions/UseSSL", false).toBool();
    m_charset = settings.value("ConnectionOptions/Charset", "utf8mb4").toString();
    m_autoReconnect = settings.value("ConnectionOptions/AutoReconnect", true).toBool();

    qDebug() << "配置文件加载成功：" << configPath;
    qDebug() << "数据库主机：" << m_host << "端口：" << m_port;
    qDebug() << "连接超时：" << m_connectTimeout << "秒，字符集：" << m_charset;
    return true;
}
